package controller

import (
	"demo/models"
	"fmt"
	"github.com/gin-gonic/gin"
	"strconv"
)

type articleController struct {}

var ArticleController = &articleController{}

func (a articleController) GetDetail(c *gin.Context)  {

	id, err := strconv.Atoi(c.Param("id"))
	if err != nil || id <= 0 {
		fmt.Print("id不能为空")
		return
	}

	article := model.Article{}

	model.DB.Debug().Where("article_id = ?", id).First(&article)

	c.JSON(200, gin.H{
		"code": 200,
		"message": "ok",
		"data": article,
	})
}

func (a articleController) GetList(c *gin.Context)  {

	pageNumber, _	:= strconv.Atoi(c.DefaultQuery("pageNum", "1"))
	pageSize, _	:= strconv.Atoi(c.DefaultQuery("pageSize", "10"))

	offset := (pageNumber - 1) * pageSize
	limit  := pageSize

	articles := make([]*model.Article, 10)

	model.DB.Debug().Offset(offset).Limit(limit).Find(&articles)

	var count int

	model.DB.Debug().Model(&model.Article{}).Count(&count)

	c.JSON(200, gin.H{
		"code": 200,
		"message": "ok",
		"data": gin.H{
			"list"	: articles,
			"count" : count,
		},
	})
}

func (a articleController) Create(c *gin.Context) {

	rawData := gin.H{
		"title": "",
		"content": "",
	}
	c.BindJSON(&rawData)

	article := model.Article{
		Title: rawData["title"].(string),
		Content: rawData["content"].(string),
		UserId: 1,
	}

	model.DB.Create(&article)

	c.JSON(200, gin.H{
		"code": 200,
		"message": "ok",
		"data": gin.H{},
	})
}

func (a articleController) Update(c *gin.Context) {

	id := c.Param("id")
	rawData := gin.H{
		"title": "",
		"content": "",
	}
	c.BindJSON(&rawData)

	fmt.Println(rawData);

	model.DB.Debug().Model(model.Article{}).Where("article_id = ?", id).Update(rawData)

	c.JSON(200, gin.H{
		"code": 200,
		"message": "ok",
		"data": gin.H{},
	})
}

func (a articleController) Delete(c *gin.Context) {

	id, _:= strconv.Atoi(c.Param("id"))

	model.DB.Debug().Delete(model.Article{ArticleId: uint64(id)})

	c.JSON(200, gin.H{
		"code": 200,
		"message": "ok",
		"data": gin.H{},
	})
}
